package com.tree.backend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tree.backend.common.Result;
import com.tree.backend.entity.Device;
import com.tree.backend.service.IDeviceService;
import lombok.RequiredArgsConstructor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**

/**
 *
 * @author tree
 * @since 2025-10-24
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/device")
public class DeviceController {

    private final IDeviceService deviceService;

    /**
     * 获取设备列表（分页+搜索）
     */
    @GetMapping("/list")
    public Result<IPage<Device>> getDeviceList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String deviceName,
            @RequestParam(required = false) String deviceType,
            @RequestParam(required = false) Boolean status) {

        Page<Device> pageParam = new Page<>(page, size);
        QueryWrapper<Device> queryWrapper = new QueryWrapper<>();

        if (StringUtils.hasText(deviceName)) {
            queryWrapper.like("device_name", deviceName);
        }
        if (StringUtils.hasText(deviceType)) {
            queryWrapper.eq("device_type", deviceType);
        }
        if (status != null) {
            queryWrapper.eq("status", status);
        }

        queryWrapper.orderByDesc("create_time");
        IPage<Device> devicePage = deviceService.page(pageParam, queryWrapper);

        return Result.success(devicePage);
    }

    /**
     * 获取设备详情
     */
    @GetMapping("/{id}")
    public Result<Device> getDeviceDetail(@PathVariable Integer id) {
        Device device = deviceService.getById(id);
        if (device == null) {
            return Result.error(401, "设备不存在");
        }
        return Result.success(device);
    }

    /**
     * 添加设备
     */
    @PostMapping
    public Result<String> addDevice(@RequestBody Device device) {
        boolean success = deviceService.save(device);
        return success ? Result.success("添加设备成功") : Result.error(401, "添加设备失败");
    }

    /**
     * 更新设备
     */
    @PutMapping("/{id}")
    public Result<String> updateDevice(@PathVariable Integer id, @RequestBody Device device) {
        device.setId(id);
        boolean success = deviceService.updateById(device);
        return success ? Result.success("更新设备成功") : Result.error(401, "更新设备失败");
    }

    /**
     * 删除设备
     */
    @DeleteMapping("/{id}")
    public Result<String> deleteDevice(@PathVariable Integer id) {
        boolean success = deviceService.removeById(id);
        return success ? Result.success("删除设备成功") : Result.error(401, "删除设备失败");
    }

    /**
     * 批量删除设备
     */
    @DeleteMapping("/batch")
    public Result<String> batchDeleteDevices(@RequestParam List<Integer> ids) {
        System.out.println("ids = " + ids);
        boolean success = deviceService.removeByIds(ids);
        return success ? Result.success("批量删除设备成功") : Result.error(401, "批量删除设备失败");
    }

    /**
     * 获取设备统计信息
     */
    @GetMapping("/stats")
    public Result<Object> getDeviceStats() {
        // 统计正常设备数量
        QueryWrapper<Device> normalWrapper = new QueryWrapper<>();
        normalWrapper.eq("status", true);
        long normalCount = deviceService.count(normalWrapper);

        // 统计故障设备数量
        QueryWrapper<Device> faultWrapper = new QueryWrapper<>();
        faultWrapper.eq("status", false);
        long faultCount = deviceService.count(faultWrapper);

        // 统计设备总数
        long totalCount = deviceService.count();

        // 返回统计信息
        return Result.success(new Object() {
            public final long total = totalCount;
            public final long normal = normalCount;
            public final long fault = faultCount;
        });
    }
}